package graph;

import com.sun.xml.internal.ws.api.model.wsdl.WSDLOutput;

import java.util.ArrayList;

/**
 * Creat with IntelliJ IDEA
 * Description:
 * User:WZW
 * Date:2022-10-23
 * Time:22:59
 */
public class GraphByMatrix {

    public char[] arrayV;//顶点数组
    public int[][] matrix;//矩阵
    private boolean isDirect;//是否有向图

    public GraphByMatrix(int size, boolean isDirect) {
        arrayV = new char[size];
        matrix = new int[size][size];
        this.isDirect = isDirect;
    }

    /**
     * 初始化
     * @param array
     */
    public void  initArrayV(char[] array) {
        for (int i = 0; i < array.length; i++) {
            arrayV[i] = array[i];
        }
    }

    /**
     * 插入边，添加权重
     * @param v1 顶点1
     * @param v2 顶点2
     * @param weight 权重
     */
    public void addEdge(char v1, char v2, int weight) {
        //1. 先查出两个顶点在顶点数组中的位置
        int index1 = getIndexOfV(v1);
        int index2 = getIndexOfV(v2);

        matrix[index1][index2] = weight;
        if (!isDirect) {
            matrix[index2][index1] = weight;
        }

    }

    /**
     * 获取顶点 v 的下标
     * @param v
     * @return
     */
    public int getIndexOfV(char v) {
        for (int i = 0; i < arrayV.length; i++) {
            if (arrayV[i] == v) {
                return i;
            }
        }
        return -1;
    }

    /**
     * 获取顶点的度
     * @param v
     * @return
     */
    public int getDevOfV(char v) {
        //1. 先在顶点数组ArrayV中找到顶点的下标
        int indexV = getIndexOfV(v);
        int count = 0;
        //2.无向图只需计算出度
        for (int i = 0; i < arrayV.length; i++) {
            if (matrix[indexV][i] != 0) {
                count++;
            }
        }
        //3.有向图的度= 出度+入度
        if (isDirect) {
            for (int i = 0; i < arrayV.length; i++) {
                if (matrix[i][indexV] != 0) {
                    count++;
                }
            }
        }
        return count;
    }

    public void printGraph() {
        for (int i = 0; i < arrayV.length; i++) {
            System.out.print(arrayV[i] + "");
        }
        System.out.println();
        for (int i = 0; i < matrix[i].length; i++) {

        }
    }


}
